<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        label="用户名称"
        prop="userName"
      >
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="手机号"
        prop="phone"
      >
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入用户手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item
        label="用户账号类型"
        prop="isAccount"
      >
        <el-select
          v-model="queryParams.isAccount"
          style="width: 240px"
        >
          <el-option
            v-for="dict in userAccountOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="用户编号"
        prop="id"
      >
        <el-input
          v-model="queryParams.id"
          placeholder="请输入用户编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="上级编号"
        prop="parentId"
      >
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入上级编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="cyan"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['admin:user:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['admin:user:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['admin:user:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['admin:user:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <!--      <el-table-column label="主键" align="center" prop="id" />
            <el-table-column label="支付宝唯一标示" align="center" prop="appAuthToken" />
            <el-table-column label="微信唯一标示" align="center" prop="openId" />-->
      <el-table-column type="expand" label="用户身份">

        <template slot-scope="props" >
          <el-table
            :data="props.row.uljoinVos"
            style="width: 100%"
            :row-class-name="tableRowClassName">
            <el-table-column
              prop="identityName"
              label="身份名称"
              width="180">
            </el-table-column>

            <el-table-column
              prop="isUse"
              label="是否使用"
              width="180">
              <template slot-scope="scope">
                {{scope.row.isUse == 1 ?'是':'否'}}
              </template>
            </el-table-column>

          </el-table>
        </template>
      </el-table-column>


      <el-table-column
        label="用户编号"
        align="center"
        prop="id"
      />
      <el-table-column
        label="用户名称"
        align="center"
        prop="userName"
      />
      <el-table-column
        label="用户手机号"
        align="center"
        prop="phone"
      />
      <el-table-column
        label="用户性别"
        align="center"
        prop="sex"
        :formatter="SexFormat"
      />
      <el-table-column
        label="用户月收入"
        align="center"
        prop="rangeMoney"
      />
      <el-table-column
        label="用户标签"
        align="center"
        prop="labels"
      />
      <el-table-column
        label="用户生日"
        align="center"
        prop="birthday"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="用户编号"
        align="center"
        prop="id"
      />
      <el-table-column
        label="用户头像"
        align="center"
        prop="headImage"
      >
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.headImage"
            :preview-src-list="[scope.row.headImage]"
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="上级编号"
        align="center"
        prop="parentId"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="findUserLevel(scope.row)"
            v-hasPermi="['admin:user:level']"
          >查看会员图谱
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:user:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['admin:user:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="90px"
        :inline="true"
      >
        <el-form-item
          label="用户名称"
          prop="userName"
        >
          <el-input
            v-model="form.userName"
            placeholder="请输入用户名称"
          />
        </el-form-item>
        <el-form-item
          label="用户手机号"
          prop="phone"
        >
          <el-input
            v-model="form.phone"
            placeholder="请输入用户手机号"

          />
        </el-form-item>
        <!--        @click="monitorPhone"-->


        <el-form-item
          label="用户生日"
          prop="birthday"
        >
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.birthday"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择用户生日"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="上级编号"
          prop="parentId"
        >

          <el-select
            filterable
            v-model="form.parentId"
            style="width: 240px"
          >
            <el-option
              v-for="dict in parentOptions"
              :key="dict.id"
              :label="dict.phone + '---' + dict.userName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="form.id"
          label="用户身份"
          prop="uiJoinIds"
        >
          <el-select v-model="form.uiJoinIds" multiple placeholder="请选择">
            <el-option
              v-for="item in uiJoinIdsList"
              :key="item.id"
              :label="item.identityName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>



        <el-form-item
          label="登陆密码"
          prop="passWord"
        >
          <el-input
            v-model="form.passWord"
            placeholder="请输入登陆密码"
          />
        </el-form-item>


        <el-form-item
          label="支付宝真实姓名"
          prop="aliUserName"
        >
          <el-input
            v-model="form.aliUserName"
            placeholder="请输入支付宝真实姓名"
          />
        </el-form-item>


        <el-form-item
          label="支付宝账号"
          prop="aliPhone"
        >
          <el-input
            v-model="form.aliPhone"
            placeholder="请输入支付宝账号"
          />
        </el-form-item>


        <el-form-item
          label="支付密码"
          prop="payPassWord"
        >
          <el-input
            v-model="form.payPassWord"
            placeholder="请输入支付密码"
          />
        </el-form-item>

        <el-form-item
          label="释放百分比"
          prop="toRelease"
        >
          <el-input
            v-model="form.toRelease"
            placeholder="请输入释放比例"
          />
        </el-form-item>

        <el-form-item
          label="性别"
          prop="sex"
        >
          <el-select
            v-model="form.sex"
            style="width: 240px"
          >
            <el-option
              v-for="dict in sexStatus"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="用户账号类型"
          prop="isAccount"
        >
          <el-select
            v-model="form.isAccount"
            style="width: 240px"
          >
            <el-option
              v-for="dict in userAccountOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="可提现"
          prop="isWithdraw"
          style="width:280px"
          v-hasPermi="['admin:user:updateUser']"
        >
          <el-radio-group
            v-model="form.isWithdraw"
            size="medium"
          >
            <el-radio
              v-for="(item, index) in isWithdrawOptions"
              :key="index"
              :label="item.value"
              :disabled="item.disabled"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="多级得消证"
          prop="disappearIsMore"
          v-hasPermi="['admin:user:updateUser']"
        >
          <el-radio-group
            v-model="form.disappearIsMore"
            size="medium"
          >
            <el-radio
              v-for="(item, index) in disappearIsMoreOptions"
              :key="index"
              :label="item.value"
              :disabled="item.disabled"
            >{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="用户头像"
          prop="headImage"
        >
          <el-upload
            class="avatar-uploader"
            :action="fileUrl"
            :show-file-list="false"
            :on-success="successFile"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="form.headImage"
              :src="form.headImage"
              class="avatar"
            >
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            />
          </el-upload>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>





    <el-dialog
      :title="userLevelTitle"
      :visible.sync="userLevelShow"
      width="1300px"
      append-to-body
    >
      <el-tabs v-model="editableTabsValue" type="card" @tab-click="tabClick" closable @tab-remove="removeTab">
        <el-tab-pane
          v-for="(item, index) in editableTabs"
          :key="item.name"
          :label="item.title"
          :name="item.name"
          :closable="item.disabled"
        >

          <el-table
            stripe
            v-loading="loading"
            :data="item.content"
          >


            <el-table-column
              label="用户名称"
              prop="userName"
              width="55"
              align="center"
            >
              <template slot-scope="scope">
                <el-button v-if="tempUserId != scope.row.id" type="primary" @click="appendUserLevel(scope.row)" round>{{scope.row.userName}}</el-button>
                <span v-else>{{scope.row.userName}}</span>
              </template>
            </el-table-column>


            <el-table-column
              label="用户手机号"
              align="center"
              prop="phone"
            />

            <el-table-column
              label="是否商户"
              align="center"
              prop="isShop"
            >
              <template slot-scope="scope">
                {{scope.row.isShop == 1 ? '是':'否'}}
              </template>
            </el-table-column>

            <el-table-column
              label="直推人数"
              align="center"
              prop="pushCount"
              sortable
            />



            <el-table-column
              label="用户等级"
              align="center"
              prop="levelName"
            />


            <el-table-column
              label="邀请码"
              align="center"
              prop="systemHost"
            />

            <el-table-column
              label="锁仓数量"
              align="center"
              prop="lockShangjia"
              sortable
            />

            <el-table-column
              label="用户释放比例"
              align="center"
              prop="toRelease"
            />

            <el-table-column
              label="消证数量"
              align="center"
              prop="disappear"
              sortable
            />


            <el-table-column
              label="积分数量"
              align="center"
              prop="integral"
              sortable
            />


            <el-table-column
              label="商甲数量"
              align="center"
              prop="shangJia"
              sortable
            />

            <el-table-column
              label="用户头像"
              align="center"
              prop="headImage"
            >
              <template slot-scope="scope">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.headImage"
                  :preview-src-list="[scope.row.headImage]"
                >
                </el-image>
              </template>
            </el-table-column>


          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>




  </div>


</template>

<script>
import {userLevel, listUser, getUser, delUser, addUser, updateUser, exportUser ,all } from "@/api/admin/user";
import { fileUrl } from "@/constant/constant"
import Editor from '@/components/Editor';

export default {
  name: "User",
  components: { Editor },
  data() {
    return {
      sexStatus: [],
      fileUrl: '',
      userLevelShow:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      editableTabs:[],
      uiJoinIdsList:[],
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      userLevelTitle:'',
      editableTabsValue:'1',
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      tempUserId:'',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        appAuthToken: null,

        openId: null,

        userName: null,

        phone: null,

        sex: null,

        rangeMoney: null,

        labels: null,

        birthday: null,

        systemHost: null,

        headImage: null,

        parentId: null,

      },
      parentOptions:[],
      userAccountOptions:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {


        userName: [
          {
            required: true,
            message: "用户名称不能为空",
            trigger: "blur",
          },
        ],

        phone: [
          { required: true, message: "用户手机号不能为空", trigger: "blur" },
        ],

        passWord: [
          {
            required: true,
            message: "登陆密码不可为空",
            trigger: "blur",
          },
        ],

        payPassWord: [
          { required: true, message: "支付密码不能为空", trigger: "blur" },
        ],

        toRelease: [
          { required: true, message: "释放比例不能为空", trigger: "blur" },
        ],
        sex: [
          { required: true, message: "性别不能为空", trigger: "blur" },
        ],
        isWithdraw: [
          { required: true, message: "是否可提现不能为空", trigger: "blur" },
        ],
        disappearIsMore: [
          { required: true, message: "是否多级反消证不可为空", trigger: "blur" },
        ],
        headImage: [
          { required: true, message: "用户头像不可为空", trigger: "blur" },
        ],
        aliUserName: [
          { required: true, message: "支付宝真实姓名不可为空", trigger: "blur" },
        ],
        aliPhone: [
          { required: true, message: "支付宝账号不可为空", trigger: "blur" },
        ],

      },
      isWithdrawOptions: [{
        "label": "是",
        "value": 1
      }, {
        "label": "否",
        "value": 0
      }],
      disappearIsMoreOptions: [{
        "label": "是",
        "value": 1
      }, {
        "label": "否",
        "value": 0
      }],
    };
  },
  /*  watch: {
      'form.phone' () {
       this.monitorPhone()
      },
      'form.userName' () {
        // this.$set(this.form, "aliUserName", this.form.userName)
      }
    },*/
  created() {
    this.fileUrl = fileUrl;
    this.getList();
    this.getDicts("sex_status").then(response => {
      this.sexStatus = response.data;
    });
    this.getDicts("user_account").then(response => {
      this.userAccountOptions = response.data;
    });
  },
  methods: {
    tableRowClassName({row, rowIndex}) {
      if (row.isUse  = 1) {
        return 'success-row';
      }
      return '';
    },
    SexFormat(row) {
      return this.selectDictLabel(this.sexStatus, row.sex);
    },
    monitorPhone(){
      this.$set(this.form, "aliPhone", this.form.phone)
      const tempPhone =  this.form.phone.substring( this.form.phone.length -6,this.form.phone.length)
      this.$set(this.form, "passWord", tempPhone)
      this.$set(this.form, "payPassWord", tempPhone)
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });

      if (this.parentOptions.length == 0){
        all().then(res =>{
          this.parentOptions = res.data;
        })
      }


    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,

        appAuthToken: null,

        openId: null,

        userName: null,

        phone: null,

        sex: null,

        rangeMoney: null,

        labels: null,

        birthday: null,

        systemHost: null,

        headImage: null,

        parentId: null,

        createBy: null,

        createTime: null,

        updateBy: null,

        updateTime: null,

      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
      this.$set(this.form, "isWithdraw", 1)
      this.$set(this.form, "isAccount", "0")
      this.$set(this.form, "sex", "1")
      this.$set(this.form, "disappearIsMore",  0)
      this.$set(this.form, "toRelease", 5)
      this.$set(this.form, "headImage", "http://shangjia1.0.obs.cn-east-3.myhuaweicloud.com/55c48d59945844f4bf423b1ceaf7df6d")



      this.uiJoinIdsList =[]
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.uiJoinIdsList = row.uljoinVos;
        // 原始赋值
        if (row.uljoinVos.length !=0){
          this.form.uiJoinIds = row.uljoinVos.map(item=>item.id);
        }
        this.open = true;
        this.title = "修改用户";
        this.form.sex = this.form.sex + "";
        this.form.isAccount = this.form.isAccount + ''
      });
    },

    tabClick(targetName){
      this.tempUserId = targetName.paneName

    },

    removeTab(targetName) {
      let tabs = this.editableTabs;
      let activeName = this.editableTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter(tab => tab.name !== targetName);
      console.log(this.editableTabs)
      this.tempUserId = activeName
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {

        if (valid) {
          if (this.form.id != null) {
            if (this.form.id === this.form.parentId){
              this.msgSuccess("当前用户不能指定上级为自己");
              this.open = false;
              return;
            }
            updateUser(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除用户编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportUser(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    successFile(res, file) {
      this.form.headImage = URL.createObjectURL(file.raw);
      this.form.headImage = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 查询会员图谱哦
    findUserLevel(row){
      this.editableTabs = []
      this.userLevelShow = true;
      this.userLevelTitle = `查看手机号为: ${row.phone} \r的用户级别关系.`

      userLevel(row.id).then(res =>{
        this.tempUserId = res.data[0].id
        this.addTab(row.id,res.data,true);
      })
    },

    appendUserLevel(row){
      this.userLevelTitle = `查看手机号为: ${row.phone} \r的用户级别关系.`
      userLevel(row.id).then(res =>{
        this.tempUserId = res.data[0].id
        this.addTab(row.id,res.data,false);
      })
    },
    addTab(targetName,userLevelList,disable) {
      let newTabName = targetName;
      this.editableTabs.push({
        title: targetName,
        name: targetName,
        content: userLevelList,
        disable:disable
      });
      this.editableTabsValue = newTabName;
    },
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-tabs__nav .el-tabs__item:nth-child(1) span {
  display: none;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>

